package com.itheima.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
//全局过滤器

/**
 * @作者 itcast
 * @创建日期 2020/12/2 15:28
 **/
@Component
@Order(-1) //越小越优先
public class LoginFilter implements GlobalFilter {
    /**
     * 过滤方法
     * @param exchange 封装 请求对象request 和 响应对象 response
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 2. 检查请求对象中是否包含 access-token参数，及参数的值是否为 admin
        Map<String, String> params = request.getQueryParams().toSingleValueMap();
        String token = params.get("access-token");
        //        包含 且值为admin  ==> 放行请求
        if(!StringUtils.isEmpty(token)&&"admin".equals(token)){
            return chain.filter(exchange);
        }else {
            //不包含 或 值不为admin  ==> 终止响应
            ServerHttpResponse response = exchange.getResponse();
            // 设置状态码  未登录状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 终止响应
        }
    }
}
